<template>
    <div class="register-container">
        <div class="register-box">
            <div class="register-header">
                <h2>用户注册</h2>
                <p>加入PMall积分商城，开启积分之旅</p>
            </div>

            <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" class="register-form"
                @submit.prevent="handleRegister">
                <el-form-item prop="username">
                    <el-input v-model="registerForm.username" placeholder="请输入用户名" size="large" prefix-icon="User"
                        clearable />
                </el-form-item>

                <el-form-item prop="password">
                    <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" size="large"
                        prefix-icon="Lock" show-password clearable />
                </el-form-item>

                <el-form-item prop="confirmPassword">
                    <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" size="large"
                        prefix-icon="Lock" show-password clearable />
                </el-form-item>

                <el-form-item prop="phone">
                    <el-input v-model="registerForm.phone" placeholder="请输入手机号" size="large" prefix-icon="Phone"
                        clearable />
                </el-form-item>

                <el-form-item prop="email">
                    <el-input v-model="registerForm.email" placeholder="请输入邮箱" size="large" prefix-icon="Message"
                        clearable />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" size="large" :loading="userStore.loading" @click="handleRegister"
                        class="register-button">
                        {{ userStore.loading ? '注册中...' : '注册' }}
                    </el-button>
                </el-form-item>
            </el-form>

            <div class="register-footer">
                <p>
                    已有账号？
                    <router-link to="/login" class="login-link">
                        立即登录
                    </router-link>
                </p>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import type { RegisterRequest } from '@/types'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const registerFormRef = ref<FormInstance>()

// 注册表单数据
const registerForm = reactive<RegisterRequest & { confirmPassword: string }>({
    username: '',
    password: '',
    phone: '',
    email: '',
    confirmPassword: ''
})

// 自定义验证函数
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请确认密码'))
    } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致'))
    } else {
        callback()
    }
}

// 表单验证规则
const registerRules: FormRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, validator: validateConfirmPassword, trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ]
}

// 处理注册
const handleRegister = async () => {
    if (!registerFormRef.value) return

    try {
        // 验证表单
        await registerFormRef.value.validate()

        // 准备注册数据
        const { confirmPassword, ...registerData } = registerForm

        // 调用注册接口
        const success = await userStore.register(registerData)

        if (success) {
            // 注册成功，跳转到登录页
            router.push('/login')
        }
    } catch (error) {
        console.error('注册失败:', error)
    }
}

// 组件挂载时检查是否已登录
onMounted(() => {
    if (userStore.isAuthenticated) {
        router.push('/')
    }
})
</script>

<style scoped>
.register-container {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20px;
}

.register-box {
    width: 100%;
    max-width: 400px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    padding: 40px;
}

.register-header {
    text-align: center;
    margin-bottom: 30px;
}

.register-header h2 {
    color: #333;
    margin-bottom: 10px;
    font-size: 28px;
    font-weight: 600;
}

.register-header p {
    color: #666;
    font-size: 14px;
}

.register-form {
    margin-bottom: 20px;
}

.register-button {
    width: 100%;
    height: 45px;
    font-size: 16px;
    font-weight: 500;
}

.register-footer {
    text-align: center;
    color: #666;
    font-size: 14px;
}

.login-link {
    color: #409eff;
    text-decoration: none;
    font-weight: 500;
}

.login-link:hover {
    text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 480px) {
    .register-box {
        padding: 30px 20px;
    }

    .register-header h2 {
        font-size: 24px;
    }
}
</style>
